var httpServer=require("./http/HttpServer.js")
var querystring = require('querystring')
var SystemEvent=require("./event/SystemEvent")
var HttpManager=Class.extend({
    _pHead:"HttpServerEvent_",
    httpServerDic:{},
    eventManager:null,
    init:function(eventManager){
        this.eventManager=eventManager;
        this.eventManager.addListener(SystemEvent.HTTP_REQUEST_END,this.onHttpRequest,this);
    },
    destruct:function(){
        this.eventManager.removeListener(SystemEvent.HTTP_REQUEST_END,this.onHttpRequest,this);
    },
    bind:function(port,certData){
        if(!this.httpServerDic[port])
            this.httpServerDic[port]=new httpServer(port,certData,this.eventManager);
    },
    unBind:function(port){
        if(this.httpServerDic[port]) {
            this.httpServerDic[port].destruct();
        }
    },
    addUrlListen:function(url,fun,thisObj,level){
        this.eventManager.addListener(this._pHead+url,fun,thisObj,level);
    },
    removeUrlListen:function(url,fun,thisObj){
        this.eventManager.removeListener(this._pHead+url,fun,thisObj);
    },
    onHttpRequest:function(port,pathname,request,response){
        var param=request.url.split("?");
        param=param[1]?querystring.parse(param[1]):{};
        var result=this.eventManager.dispatchEvent(this._pHead+pathname,[port,param,request,response]);
        if(result)
            this.eventManager.preventDefault();
    }
})

module.exports=HttpManager;